package com.wqd.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqd.article.mapper.ApArticleConfigMapper;
import com.wqd.article.mapper.ApArticleContentMapper;
import com.wqd.article.mapper.ApArticleMapper;
import com.wqd.article.service.IApArticleService;
import com.wqd.article.vos.HotArticleVo;
import com.wqd.common.constants.ArticleConstants;
import com.wqd.model.article.dtos.ArticleDto;
import com.wqd.model.article.dtos.ArticleHomeDto;
import com.wqd.model.article.pojos.ApArticle;
import com.wqd.model.article.pojos.ApArticleConfig;
import com.wqd.model.article.pojos.ApArticleContent;
import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.common.enums.AppHttpCodeEnum;
import com.wqd.model.mess.ArticleVisitStreamMess;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerServiceImpl articleFreemarkerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //健壮代码
        if(dto.getSize() == null || dto.getSize() == 0){
            dto.setSize(10);
        }
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间校验
        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }

        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 保存和修改文章内容+文章配置+文章信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult save(ArticleDto dto) {
        if(dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle apArticle = null;
        if(dto.getId() == null){
            //没有id代表新增
            apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            int row = apArticleMapper.insert(apArticle);
            if(row < 1){
                throw new RuntimeException("文章插入失败");
            }
            //保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

             //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);
        }else {
            //能走到这里是修改
            //先获取原文章
            apArticle = apArticleMapper.selectById(dto.getId());
            if(apArticle != null){
                BeanUtils.copyProperties(dto,apArticle);
                apArticleMapper.updateById(apArticle);
                //先拿到文章内容对象
                ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                        Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
                apArticleContent.setContent(dto.getContent());
                apArticleContentMapper.updateById(apArticleContent);
            }
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle,dto.getContent());

        //返回文章id
        return ResponseResult.okResult(apArticle == null ? "" : apArticle.getId());
    }

    /**
     * 文章列表查询Plus首页,查询的就是首页
     *
     * @param dto,推荐频道  __all__  如果其他频道则是id
     * @return
     */
    @Override
    public ResponseResult loadArticleListNew(ArticleHomeDto dto) {
        //把缓存到redis中的热点文章数据取出来
        String hotArticleListStr = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        //转化类型
        List<HotArticleVo> hotArticleVoList = JSONArray.parseArray(hotArticleListStr, HotArticleVo.class);

        return ResponseResult.okResult(hotArticleVoList);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //更新文章的阅读,点赞,收藏,评论数量
        ApArticle apArticle = updateArticle(mess);
        //计算文章的分值
        Integer score = calcScore(apArticle) * 3;
        //替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //替换推荐的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换当前文章对应频道的热点数据
     * @param apArticle
     * @param score
     * @param channel
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String channel) {
        String articleListStr = redisTemplate.opsForValue().get(channel);
        if (StringUtils.isNotBlank(articleListStr)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true ;

            //如果缓存中存在文章,则只需要更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())){
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }
            //如果缓存中不存在文章,查询缓存中分值最小的一条数据,进行分值的比较,如果当前文章的分值大于缓存中的数据,就替换
            if (flag){
                if (hotArticleVoList.size() >= 30){
                    //开始替换文章
                    //获取分值最低的文章
                    HotArticleVo lastArticle = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore)
                            .reversed()).collect(Collectors.toList())
                            .get(hotArticleVoList.size() - 1);
                    if (lastArticle.getScore() < score){

                        hotArticleVoList.remove(lastArticle);
                        HotArticleVo vo = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle,vo);
                        vo.setScore(score);
                        hotArticleVoList.add(vo);
                    }
                }else{
                    HotArticleVo vo = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle,vo);
                    vo.setScore(score);
                    hotArticleVoList.add(vo);
                }
            }

            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore)
                    .reversed()).collect(Collectors.toList());
            redisTemplate.opsForValue().set(channel,JSON.toJSONString(hotArticleVoList));
        }
    }

    /**
     * 计算文章总分值
     * @param apArticle
     * @return
     */
    private Integer calcScore(ApArticle apArticle) {
        return apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT
                + apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT
                + apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT
                + apArticle.getViews();
    }

    /**
     * 更新文章的阅读,点赞,收藏,评论数量的方法
     * @param mess
     * @return
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;
    }
}
